package com.zy.core.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zy.pro.system.model.Employee;
import com.zy.utils.SessionUtils;

public class EmployeeFilter implements Filter {

	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		
		// 不过滤的uri
		String[] notFilter = new String[] { 
				"/control/system/employeeController/login.do"
		};
		
		// 请求的uri
		String uri = request.getRequestURI();
		if (uri.indexOf(".do") != -1) {
			boolean doFilter = true;
			for (String s : notFilter) {
				if (uri.indexOf(s) != -1) {
					// 如果uri中包含不过滤的uri，则不进行过滤
					doFilter = false;
					break;
				}
			}

			if (doFilter) {
				Employee employee = SessionUtils.getEmpl(request);
				if(employee==null){
					// 如果session中不存在登录者实体，则弹出框提示重新登录
					// 设置request和response的字符集，防止乱码
					HttpServletResponse response = (HttpServletResponse) res;
					request.setCharacterEncoding("UTF-8");
					response.setCharacterEncoding("UTF-8");
					PrintWriter out = response.getWriter();
					StringBuilder builder = new StringBuilder();
					builder.append("<script type=\"text/javascript\">");
//					builder.append("alert('网页过期，请重新登录！');");
					builder.append("window.top.location.href='");
					builder.append(request.getScheme());
					builder.append("://");
					builder.append(request.getServerName());
					builder.append(":");
					builder.append(request.getServerPort());
					builder.append(request.getContextPath());
//					builder.append("/system/logonController/login.do");
					builder.append("';");
					builder.append("</script>");
					out.print(builder.toString());
					
//					String tagetLoginPath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+ "/system/logonController/login.do";
//					response.sendRedirect(tagetLoginPath);
//					request.getRequestDispatcher("/system/logonController/login.do").forward(request, response);
					
				}else{
					chain.doFilter(req, res);
				}
			} else {
				chain.doFilter(req, res);
			}

		} else {
			chain.doFilter(req, res);
		}
		//chain.doFilter(req, res);
		
	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
